package front_comment_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type CommentDelReq struct {
	ID        uint `json:"id"` // 评论id
	ArticleID uint `json:"article_id"`
}

func (CommentApi) CommentDel(c *gin.Context) {
	var req CommentDelReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	var comment models.CommentModel
	err := global.DB.First(&comment, req.ID).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		// 修改文章评论数
		if err := tx.Exec("update article set comment_count = comment_count - 1 where id = ?", req.ID).Error; err != nil {
			return err
		}
		// 有父评论修改父评论数
		if comment.ParentCommentID != nil {
			err2 := tx.Exec("update comment set comment_count = comment_count - 1 where id = ?", comment.ParentCommentID).Error
			if err2 != nil {
				return err2
			}
		}
		err2 := tx.Where("parent_comment_id = ?", req.ID).Delete(&models.CommentModel{}).Error
		if err2 != nil {
			return err2
		}
		err2 = tx.Delete(comment).Error
		if err2 != nil {
			return err2
		}
		return nil
	})
	res.OkWithMessage("成功删除", c)
}
